const app = getApp()
const adapters = require("../../utils/adapters");
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      title: '绑定商户',
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight,
      tabbarHeight: app.globalData.tabbarHeight,
      screenHeight: app.globalData.screenHeight
    },
    businessList: [],
    user: {},
    activeNames: null,
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },

  onChange(event) {
    this.setData({
      activeNames: event.detail
    });
  },
 
  async onLoad(options) {
    const that = this
    wx.getStorage({
      key: "user",
      success(res) {
        console.log("获取的数据为", res.data);
        that.setData({user: res.data})
      },
      fail(err) {
        console.error("读取数据失败", err);
      }
    });
    const getBusinessListRes = await adapters.getBusinessList();
    if(getBusinessListRes.success) {
      this.setData({
        "businessList": getBusinessListRes.data
      })
    } else {
      wx.showToast({
        title: '商户信息获取失败！',
        icon: 'none'
      })
    }
    const bindBusinessIndex = getBusinessListRes.data.findIndex(item => item.businessId === this.data.user.bindBusinessId)
    this.setData({
      activeNames: bindBusinessIndex
    })
  },

  async bindBusiness(e) {
    const businessId = e.currentTarget.dataset.id;
  
    try {
      await Dialog.confirm({
        title: '再次确认',
        message: '是否绑定该ID为 ' + businessId + ' 的商户？',
      });
  
      const bindBusinessRes = await adapters.bindBusiness(businessId);
      if (bindBusinessRes.success) {
        wx.showToast({ title: '绑定成功！' });
      } else {
        wx.showToast({
          title: '绑定失败',
          icon: 'none'
        });
      }
    } catch (err) {
      // 用户点击取消或请求失败
      console.log('取消绑定或出错', err);
    }
  },

})